<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\yperp\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\yperp\common\ExcelTools;
use app\yperp\job\YpOrderAsync;
use app\yperp\job\YpOrderExpr;
use app\yperp\logic\yp\YpExpress;
use app\yperp\model\GoodsSkuStandby;
use app\yperp\model\Supplier;
use Fastposter\Client;
use app\admin\model\Attachment as AttachmentModel;
use app\yperp\logic\yp\YpOrder as LogicypOrder;
use app\yperp\model\YpOrderGoods as ModelYpOrderGoods;
use app\yperp\model\YpOrder as ModelYpOrder;
use think\Db;
use think\Image;
use think\Queue;

/**
 * 品牌控制器
 * @package app\yperp\admin
 */
class Yporder extends Admin
{
    /**
     * 品牌列表
     * @author 蔡伟明 <314013107@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        // 查询
        $map = $this->getMap();
        // 排序
        $order = $this->getOrder('createTime desc');
        // dump($map);
        $expr = null;
        foreach ($map as $key => $value) {
            if ($value[0] == 'expr') {
                unset($map[$key]);
                $expr = $value[2];
            }
        }
        // 数据列表
        $exprs = [];
        if ($expr !== null) {
            $exprs = [['expr_code', '=', 'not null']];
        }
        $data_list = ModelYpOrderGoods::withJoin('yporder')->where($exprs)->where($map)->order($order)->paginate();
        // dump($data_list);die;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            // ->setPageTips('debug:' . Db::getLastSql(), 'warning')

            ->addTopButton('pull', [
                'title' => '聚水潭发货单',
                'icon'  => 'fa fa-fw fa-shopping',
                'field' => 'id',
                'target-form' => 'ids',
                'class' => 'btn btn-success ajax-post confirm',
                'href'  => (string)url('add')
            ])
            ->addTopButton('ypasync', [
                'title' => '同步小程序订单',
                'icon'  => 'fa fa-fw fa-shopping',
                'class' => 'btn btn-success ajax confirm',
                'href'  => (string)url('ypasync')
            ])

            ->addTopButton('push', [
                'title' => '导出筛选',
                'icon'  => 'fa fa-fw fa-upload',
                'class' => 'btn btn-success',
                'href'  => url('download', ['type' => 'select', 'map' => base64_encode(json_encode($map))]),
            ])
            ->addTopButton('push', [
                'title' => '导出所有',
                'icon'  => 'fa fa-fw fa-upload',
                'class' => 'btn btn-success',
                'href'  => url('download', ['type' => 'all']),
            ])
            ->addRightButton('pushexpress', [
                'title' => '发货',
                'icon'  => 'fa fa-fw fa-rss-square',
                'class' => 'ajax-get',
                'href'  => url('pushexpress', ['orderCode' => '__orderCode__'])
            ])
            ->replaceRightButton(function ($data) {
                return $data['expr_code'] == null;
            }, '', 'pushexpress')
            ->addTopSelect('status', '订单状态', LogicypOrder::ORDER_STATUS_MAP)
            ->addTopSelect('expr', '发货', ['未发货', '已发货'])
            ->setSearch([
                'mainOrderCode' => '主订单号',
                'orderCode' => '订单号',
                'status' => '订单状态',
                'deliveryStatus' => '发货状态',
                'receiverName' => '收货人姓名',
                'receiverPhone' => '收货人电话',
            ]) // 设置搜索框

            ->addColumns([ // 批量添加数据列
                ['id', 'ID'],
                ['mainOrderCode', '主订单号', 'text'],
                ['orderCode', '订单号', 'text'],
                ['right_button', '操作', 'btn'],
                ['status', '订单状态', 'text', '', LogicypOrder::ORDER_STATUS_MAP],
                // ['deliveryStatus', '发货状态', 'text', '', LogicypOrder::ORDER_STATUS_MAP],
                ['goodsName', '商品名称', 'text'],
                ['goodsCode', '物料编码', 'text'],
                ['buyNum', '数量', 'text'],
                ['expr_code', '运单号', 'text'],
                ['expr_corp', '快递公司', 'text'],
                // ['memberId', '会员ID', 'text'],
                // ['nickName', '会员昵称', 'text'],
                // ['phone', '联系电话', 'text'],
                ['receiverName', '收货人姓名', 'text'],
                ['receiverPhone', '收货人电话', 'text'],
                ['receiverProvince', '收货人省份', 'text'],
                ['receiverCity', '收货人城市', 'text'],
                ['receiverRegion', '收货人区县', 'text'],
                ['receiverStreet', '收货人街道', 'text'],
                ['receiverDetailAddress', '收货人详细地址', 'text'],

                ['realPayAmount', '实际支付金额', 'text'],
                ['promotionAmount', '优惠金额', 'text'],
                ['integrationAmount', '积分金额', 'text'],
                ['couponAmount', '优惠券金额', 'text'],
                ['createTime', '订单创建时间', 'text'],
            ])
            ->addOrder('createTime')
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板
    }

    public function pushexpress($orderCode)
    {
        $res =    Queue::push(YpOrderExpr::class, $orderCode);

        if ($res) {
            $this->success('推送成功');
        } else {
            $this->error('推送失败');
        }
    }
    /**
     * 新增
     * @author 蔡伟明 <314013107@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function add()
    {
        $ids =  $this->request->param('ids');

        $ids = join(',', $ids);
        $orders = ModelYpOrder::whereIn('id', $ids)->where('status', 2)->select()->toArray();
        dump($orders);
    }

    public function download()
    {
        $type = $this->request->param('type', 'all');
        $map = $this->request->param('map', []);
        $data_list = [];
        switch ($type) {
            case 'select':
                if ($map) {
                    $map = json_decode(base64_decode($map), true);
                } else {
                    $this->error('参数错误');
                }
            case 'all':
            default:
                $map[0][0] = 'yporder.status';
                $data_list = ModelYpOrderGoods::withJoin(['yporder', 'ypgoods'], 'LEFT')
                    // ->withJoin('ypgoods','LEFT')
                    ->where($map)
                    ->order('createTime desc')->select()->toArray();
        }

        foreach ($data_list as &$value) {
            unset($value['yporder']);
            unset($value['ypgoods']);
        }

        $title = [
            ['title' => '线上订单号', 'name' => 'orderCode',],
            ['title' => '下单时间', 'name' => 'createTime',],
            ['title' => '买家帐号（必填）', 'name' => 'memberId',],
            // ['title' => '收款账号', 'name' => 'asaa'],
            ['title' => '收款账号', 'name' => ''],
            ['title' => '支付单号', 'name' => ''],
            ['title' => '付款方式', 'name' => ''],
            ['title' => '付款时间（不填写订单导入后为待支付状态）', 'name' => 'paydatetime', 'func' => function ($value, $data) {
                return   $data['createTime'];
            }],
            ['title' => '卖家备注', 'name' => ''],
            ['title' => '买家留言', 'name' => ''],
            ['title' => '运费', 'name' => ''],
            ['title' => '应付金额', 'name' => ''],
            ['title' => '收货人姓名（必填）', 'name' => 'receiverName'],
            ['title' => '手机（必填）', 'name' => 'receiverPhone'],
            ['title' => '固话', 'name' => ''],
            ['title' => '省份（必填）', 'name' => 'receiverProvince'],
            ['title' => '城市（必填）', 'name' => 'receiverCity'],
            ['title' => '区县（必填）', 'name' => 'receiverRegion'],
            ['title' => '地址（必填）', 'name' => 'receiverDetailAddress', 'func' => function ($value, $data) {
                return   $data['receiverStreet'] . $value;
            }],
            ['title' => '邮编', 'name' => ''],
            ['title' => '线上商品编码', 'name' => 'goodsCode'],
            ['title' => '商品编码（必填）', 'name' => 'itemCode'],
            ['title' => '商品名称', 'name' => 'itemName'],
            ['title' => '颜色及规格', 'name' => 'colour',],
            [
                'title' => '数量（必填）', 'name' => 'buyNum',
                'func' => function ($value, $data) {
                    $buyNum = GoodsSkuStandby::where(['itemCodeAlias' => $data['goodsCode']])->value('buy_number');
                    // dump($buyNum);
                    return   $value * $buyNum;
                }
            ], //buy_number
            ['title' => '商品单价（必填）', 'name' => 'regulatePriceMax', 'func' => function ($value, $data) {

                if ($value > 0) {
                    return $value;
                }
                if ($data['sell_market_price'] > 0) {
                    return $data['sell_market_price'] * 1.3;
                } elseif ($data['sell_daily_price'] > 0) {
                    return $data['sell_daily_price'];
                } elseif ($data['sell_activity_price'] > 0) {
                    return $data['sell_activity_price'];
                }
            }],
            ['title' => '生产批次', 'name' => ''],
            ['title' => '生产日期', 'name' => ''],
            ['title' => '快递公司', 'name' => ''],
            ['title' => '快递单号', 'name' => ''],
            ['title' => '发货时间', 'name' => ''],
            ['title' => '状态', 'name' => ''],
            ['title' => '业务员', 'name' => ''],
            ['title' => '便签|线下备注', 'name' => ''],
            ['title' => '店铺名称', 'name' => ''],
        ];
        // dump($data_list);die;
        $EXCEL =  ExcelTools::outputProjectExcel($data_list, ['titles' => $title, 'file_name' => '聚水潭货单-', 'sheet_name' => '订单信息', 'no_title' => true, 'is_order' => false]);
        ExcelTools::downloadExcel($EXCEL, '聚水潭货单-' . date('Y_m_d_His'));
    }

    public function ypasync()
    {
        // LogicypOrder::getInstance()->getList();

        $res = Queue::push(YpOrderAsync::class, null);
        if ($res) {
            return $this->success('推送同步成功');
        } else {
            return $this->error('推送同步失败');
        }
    }
}
